import uuid

from pymysql import connect
from pymysql.cursors import DictCursor


class MySQLTools(object):
    def __init__(self):
        self.conn = connect(
            host='106.15.65.91',
            port=3306,
            user='root',
            passwd='123456.',
            db='test_lmy',
            cursorclass=DictCursor
        )
        self.cursor = self.conn.cursor()

    def search(self, table_name, *args, **kwargs):
        sql = 'select * from {}'.format(table_name)
        try:
            self.cursor.execute(sql, args=kwargs)
            res = self.cursor.fetchall()
        except Exception as e:
            res = {'code': -1, 'msg': e}
        return res

    def insert(self, table_name, *args, **kwargs):
        save_sql = "insert into %s(id, username, password)values(%s)"
        insert_values = ",".join(["%({})s".format(key) for key in kwargs])
        sql = save_sql % (table_name, insert_values)
        try:
            self.cursor.execute(sql, args=kwargs)
            self.conn.commit()
            res = {'code': 0, 'msg': 'success'}
        except Exception as e:
            res = {'code': -1, 'msg': e}
        finally:
            self.conn.close()
        return res

    def delete(self, *args, **kwargs):
        pass

    def update(self, *args, **kwargs):
        pass
